package com.kr.aia.powerrp.dropbox;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;

import com.kr.aia.powerrp.db.CustomerInfoVO;
import com.kr.aia.powerrp.roleplay.RPDataListAdapter;
import com.kr.aia.powerrp.R;
import com.kr.aia.powerrp.R.drawable;
import com.kr.aia.powerrp.R.id;
import com.kr.aia.powerrp.R.layout;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class DropBoxLocalListView extends View{
	private String rootPath;
	private String initDir;
	private Boolean isRP;
	public VideoDataListAdapter videoAdapter;
	private Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.ic_launcher);
	
	ArrayList<String> videoList = new ArrayList<String>();
	ArrayList<VideoDataStruct> tInfoList = new ArrayList<VideoDataStruct>();
	
	public Uri intentUri = null;
	
	public Uri getIntentUri(){
		return this.intentUri;
	}
	
	public void setIntentUri(Uri intentUri){
		this.intentUri = intentUri;
	}
	
	public ArrayList<VideoDataStruct> getVideoListInfo(){
		return tInfoList;
	}
    
	public DropBoxLocalListView(Context context, String dirname, Boolean isRP) {
		super(context);
		this.rootPath = Environment.getExternalStorageDirectory().getPath() + "/powerRP/";
		this.initDir = dirname;
		this.isRP = isRP;
	}

	public View openMovieClipListView() {
	    LinearLayout linearLayoutView = new LinearLayout(getContext());
	    
	    /*
	    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    ListView listview = (ListView) inflater.inflate(R.layout.common_mc_listview, null);
	    listview.setCacheColorHint(0xffffffff);
	    */
	    
	    
	    ListView listview = new ListView(getContext());
	    listview.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
	    listview.setSelector(R.drawable.list_selector);
	    //listview.setSelector(android.R.color.darker_gray);
	    //listview.setSelector(new ColorDrawable(0x000000));
	    
	    //ListView listview = new ListView(null, null);  new ListView(getContext());
	    
	    //listview.setSelector(R.drawable.setting_contact_list_selector);
	    //listview.setCacheColorHint(0xffffffff);
	    
	    getVideoList(rootPath, initDir);
	    
	    
	    videoAdapter = new VideoDataListAdapter(this.getContext(), R.layout.dropbox_videolist_popup, tInfoList);
	    videoAdapter.notifyDataSetChanged();
	    listview.setAdapter(videoAdapter);
	    listview.setOnItemClickListener(itemClickListener);
	    
	    // RP화면에서 호출 된 경우, 썸네일 가져오는 프로세스 생략.
	    if(!isRP){
	        for(int i = 0 ; i < videoList.size() ; i++){
	        	thumbnailTask tTask = new thumbnailTask();
	            tTask.execute(i);
	        }
	    }
        
	    linearLayoutView.setOrientation(LinearLayout.VERTICAL);
	    linearLayoutView.addView(listview);
	    return linearLayoutView;
	}
	
	
	protected void getVideoList(String dPath, String dirName){
		try{
			File filePath = new File(dPath + dirName);
			File[] fileList = filePath.listFiles();
			
			String fileType = "mp4";
			if(isRP){
				fileType = "txt";
			}
			
			int fileListLen = 0;
			if(fileList != null){
				fileListLen = fileList.length;
			}
			
			for(int i = 0; i < fileListLen; i++){
				if(fileList[i].isFile() && fileList[i].getName().endsWith(fileType)){
					String fileNameLabel = (isRP ? fileList[i].getName() : (dirName).toUpperCase() + " - " + fileList[i].getName());
					VideoDataStruct tmpData = new VideoDataStruct(dPath + dirName + "/" + fileList[i].getName(), fileNameLabel);
					tInfoList.add(tmpData);
					videoList.add(dPath + dirName + "/" + fileList[i].getName());
				}else if(fileList[i].isDirectory()){
					getVideoList(dPath + dirName, fileList[i].getName());
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	protected void refreshView(){
		tInfoList.clear();
		videoList.clear();
		
		getVideoList(rootPath, initDir);
	    videoAdapter.notifyDataSetChanged();
	}
	
	protected class VideoDataListAdapter extends ArrayAdapter<VideoDataStruct> {
		
		private Context context;
	    private int layoutResourceId;
	    private ArrayList<VideoDataStruct> items;
	    private int curPosition = -1;

	    public VideoDataListAdapter(Context context, int textViewResourceId, ArrayList<VideoDataStruct> items) {
	    	super(context, textViewResourceId, items);
	    	this.context = context;
	    	this.layoutResourceId = textViewResourceId;
	        this.items = items;
	    }
	    
	    @Override
	    public int getCount() {
	        return items.size();
	    }
	    
	    public void setSelectedItem(int position){
	    	this.curPosition = position;
	    }
	    
	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	    	View row = convertView;
    		if(row == null){
    			LayoutInflater inflater = ((Activity)context).getLayoutInflater();
    			row = inflater.inflate(layoutResourceId, parent, false);
    		}
    		
    		VideoDataStruct cItem = super.getItem(position);
    		
    		if(cItem != null){
	    		TextView textfilePath = (TextView)row.findViewById(R.id.FilePath);
	    		textfilePath.setText(cItem.getFileName());
	    		
	    		ImageView imageThumbnail = (ImageView)row.findViewById(R.id.Thumbnail);
	    		if(cItem.getThumbnailImage() != null){
	    			imageThumbnail.setImageBitmap(cItem.getThumbnailImage());
	    		}
	    		
	    		// RP화면에서 호출 된 경우, 썸네일 숨김.
	    		if(isRP){
	    			imageThumbnail.setVisibility(View.GONE);
	    		}
	    		
	    		
	    		
	    		if(cItem.isSelected){
	    			row.setBackgroundResource(R.drawable.gradient_bg_hover);
	    		}else{
	    			row.setBackgroundResource(R.drawable.gradient_bg);
	    		}
	    		
	    		//Log.e("RPR", "" + curPosition + " -- " + position);
	    		
	    		/*
	    		if(curPosition == position){
    	    		row.setBackgroundResource(R.drawable.gradient_bg_hover);
    	    	}else{
    	    		row.setBackgroundResource(R.drawable.gradient_bg);	
    	    	}*/
    		}

    		return row;
	    }
	}
	

    private class thumbnailTask extends AsyncTask<Integer, Void, Integer> {
		@Override 
		protected Integer doInBackground(Integer... fileIdx) {
			//Log.e("PRP", "Thumbnail Video ----------------- " + videoList.get(fileIdx[0]));
			Bitmap tmpImage = ThumbnailUtils.createVideoThumbnail(videoList.get(fileIdx[0]), Thumbnails.MICRO_KIND);
			
			if(tInfoList.get(fileIdx[0]).getThumbnailImage() != null){
				return -9;
			}
			
			tInfoList.get(fileIdx[0]).setThumbnailImage(tmpImage);
			
			//Log.e("PRP", "----------------- " + tInfoList.get(i).getFilename());
			return 0;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			if(result == 0){
				videoAdapter.notifyDataSetChanged();
			}
		}

	}
    
    private OnItemClickListener itemClickListener = new OnItemClickListener(){
    	@Override
    	public void onItemClick(AdapterView<?> parent, View clickedView, int pos, long id){
    		
    		VideoDataStruct tmp = (VideoDataStruct)parent.getAdapter().getItem(pos);
    		((VideoDataListAdapter) videoAdapter).setSelectedItem(pos);
    		
    		if(tInfoList.get(pos).isSelected){
    			tInfoList.get(pos).isSelected = false;
    		}else{
    			tInfoList.get(pos).isSelected = true;
    		}
    		
    		videoAdapter.notifyDataSetChanged();
    		
    		
    		setIntentUri(Uri.parse(tInfoList.get(pos).getFilePath()));
    	}
    };

    
    
    class VideoDataStruct{
		Bitmap thumbnailImage;
		String fileName;
		String filePath;
		Boolean isSelected = false;
		
		public VideoDataStruct(String filepath, String filename){
			this.fileName = filename;
			this.filePath = filepath;
		}
		
		public Bitmap getThumbnailImage(){
			return thumbnailImage;
		}
		
		public void setThumbnailImage(Bitmap imgage){
			this.thumbnailImage = null;
			this.thumbnailImage = imgage;
		}
		
		public String getFileName(){
			return fileName;
		}
		
		public String getFilePath(){
			return filePath;
		}
		
	}
}